function Snake(el){
    this.el = el
    //保存蛇的长度
    this.length = 20
    //存蛇
    this.snakeObj = [
        {x:3, y:2, color:'red', ele:null},
        {x:2, y:2, color:'blue', ele:null},
        {x:1, y:2, color:'blue', ele:null},
    ]
    // 方向
    this.direction = 'right'
}

Snake.prototype.remove = function(){
    for(let i=0; i<this.snakeObj.length; i++){
        if(this.snakeObj[i].el){
            this.el.removeChild(this.snakeObj[i].el)
        }  
    }
}

Snake.prototype.create = function(){
    this.remove()
    for(let i=0; i<this.snakeObj.length; i++){
        //创建蛇标签对象
        let snakedivObj = document.createElement('div')
        //设置蛇标签对象的样式
        snakedivObj.style.width = this.length + 'px'
        snakedivObj.style.height = this.length + 'px'
        snakedivObj.style.background = this.snakeObj[i].color
        //设置蛇的坐标
        snakedivObj.style.position = 'absolute'
        snakedivObj.style.left = this.snakeObj[i].x *this.length + 'px'
        snakedivObj.style.top = this.snakeObj[i].y *this.length + 'px'
        //展示在页面上
        this.el.appendChild(snakedivObj)

        // 单独保存下蛇节对象
        this.snakeObj[i].el = snakedivObj
    }
}
Snake.prototype.move = function(){
    //将snake构造函数中蛇的数据+1
    // for(let i=0; i<this.snakeObj.length; i++){
    //     this.snakeObj[i].x += 1
    // }
    //控制蛇头
    for (let i = this.snakeObj.length - 1; i>0; i--) {
        this.snakeObj[i].x = this.snakeObj[i-1].x
        this.snakeObj[i].y = this.snakeObj[i-1].y
    }
    switch (this.direction) {
        case 'left':
            if(this.snakeObj[0].x == 0){
                clearInterval(t)
                alert('撞到墙，游戏结束')
            }
            this.snakeObj[0].x -= 1
            break;
        case 'top':
            if(this.snakeObj[0].y == 0){
                clearInterval(t)
                alert('撞到墙，游戏结束')
            }
            this.snakeObj[0].y -= 1
            break;
        case 'right':
            if(this.snakeObj[0].x == 39){
                clearInterval(t)
                alert('撞到墙，游戏结束')
            }
            this.snakeObj[0].x += 1
            break;
        case 'bottom':
            if(this.snakeObj[0].y == 19){
                clearInterval(t)
                alert('撞到墙，游戏结束')
            }
            this.snakeObj[0].y += 1
            break;
    }

    //重新创建
    this.create()
}